﻿using Common.Json;
using MSATracert;
using Refit;
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Net.Http;
using System.Text;
namespace Common.Refit
{
    //public class TestClient : ContractConstructorBase
    //{ 
    
    //}
    /// <summary>
    /// 契约构造器
    /// </summary>
    public abstract class ContractConstructorBase
    {
        public ConcurrentDictionary<string, HttpClient> hosts = new ConcurrentDictionary<string, HttpClient>();

        private RefitSettings Settings { get; set; }

        public abstract string ServiceName { get; }

        public T CreateConstructorInstances<T>()
        {
            var host = GetServiceHost();
            var http = CreateHttpClientInstances(host);
            var refitSettings = CreateRefitSettingsInstances();
            return RestService.For<T>(http, refitSettings);
        }
        /// <summary>
        /// 获取服务地址
        /// </summary>
        /// <returns></returns>
        private string GetServiceHost()
        {
            return string.Empty;
            //var serviceName = AppConfig.OpenApiServiceName;
            //if (ConfigureService == null)
            //{
            //    throw new Exception($"[{serviceName}]未指定ConfigureService源");
            //}
            //var host = ConfigureService(serviceName);
            //if (string.IsNullOrWhiteSpace(host))
            //{
            //    throw new Exception($"[{serviceName}]无效的ServiceHost");
            //}
            //return host;
        }

        private HttpClient CreateHttpClientInstances(string serviceHost)
        {
            var httpClient = hosts.GetOrAdd(serviceHost, (host) =>
              {
                  HttpClient client = new HttpClient(new LinkTracertHttpHandler(true));
                  client.BaseAddress = new Uri(host);
                  return client;
              });
            return httpClient;
        }

        private RefitSettings CreateRefitSettingsInstances()
        {
            if (Settings != null)
            {
                return Settings;
            }
            Settings = new RefitSettings();
            RefitSettingsConfiguration(Settings);
            return Settings;
        }

        protected virtual void HttpClientConfiguration(HttpClient client)
        {

        }

        protected virtual void RefitSettingsConfiguration(RefitSettings settings)
        {
        }
    }
}
